package com.hongkuncheng.cms.controller.admin.system;

import java.io.*;

import org.apache.tomcat.util.http.fileupload.FileItemIterator;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.DateHelper;
import com.hongkuncheng.cms.helper.FileHelper;
import com.hongkuncheng.cms.ueditor.upload.StorageManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 文件处理
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/system/file")
public class AfileController extends BaseController {

    // 上传文件
    @RequestMapping("upload")
    @ResponseBody
    public void upload() throws Exception {
        FileItemStream fileStream = null;
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            fileStream = iterator.next();
            if (!fileStream.isFormField())
                break;
            fileStream = null;
        }
        if (fileStream == null) {
            print("未找到上传数据");
            return;
        }
        InputStream is = fileStream.openStream();
        String savepath = request.getParameter("savepath");
        String realpath = null;
        if (savepath != null) {
            if (savepath.contains(":") || savepath.startsWith("/")) {
                realpath = savepath;
            } else if (savepath.startsWith("-")) {
                savepath = savepath.substring(1);
                realpath = applicationDirectory + savepath;
            } else {
                savepath = "/upload/" + savepath;
                realpath = applicationDirectory + savepath;
            }
        } else {
            String editorpath = null;
            if (request.getSession().getAttribute("editorpath") != null)
                editorpath = request.getSession().getAttribute("editorpath").toString();
            else
                editorpath = "visitor";
            savepath = "/upload/" + editorpath + "/";
            savepath += fileStream.getContentType().startsWith("image/") ? "image" : "file";
            savepath += "/" + DateHelper.getDirectory();
            realpath = applicationDirectory + savepath;
        }
        File destdir = new File(realpath);
        if (!destdir.exists()) destdir.mkdirs();
        String filename = null;
        String nametype = request.getParameter("nametype");
        if (nametype == null) {
            filename = DateHelper.getFileName(getExt(fileStream.getName()));
        } else {
            switch (Integer.parseInt(nametype)) {
                case 1:
                    filename = fileStream.getName();
                    break;
                case 2:
                    filename = request.getParameter("assignname");
                    break;
            }
        }
        File destfile = new File(destdir, filename);
        try {
            byte[] dataBuf = new byte[2048];
            BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(destfile), StorageManager.BUFFER_SIZE);
            int count = 0;
            while ((count = bis.read(dataBuf)) != -1) {
                bos.write(dataBuf, 0, count);
            }
            bos.flush();
            bos.close();
            print(FileHelper.Exists(realpath + "/" + filename) ? savepath + "/" + filename : "error");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取文件拓展名
    private String getExt(String fileName) {
        return fileName.substring(fileName.indexOf("."));
    }

}
